﻿using Nop.Core;
using Nop.Services.Media;
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace Nop.Web.Controllers
{
    public class FileController : BasePublicController
    {
        private readonly IFilesService _filesService;
        public FileController(IFilesService filesService)
        {
            this._filesService = filesService;
        }

        [HttpPost]
        public virtual ActionResult AsyncUpload()
        {
            Stream stream = null;
            var fileName = "";
            var contentType = "";
            if (String.IsNullOrEmpty(Request["qqfile"]))
            {
                HttpPostedFileBase httpPostedFile = Request.Files[0];
                if (httpPostedFile == null)
                    throw new ArgumentException("No file uploaded");
                stream = httpPostedFile.InputStream;
                fileName = Path.GetFileName(httpPostedFile.FileName);
                if (!string.IsNullOrEmpty(Request.Form["filename"]))
                {
                    // 自动以文件名
                    fileName = Request.Form["filename"];
                }
                contentType = httpPostedFile.ContentType;
            }
            else
            {
                //Webkit, Mozilla
                stream = Request.InputStream;
                fileName = Request["qqfile"];
            }

            var fileBinary = new byte[stream.Length];
            stream.Read(fileBinary, 0, fileBinary.Length);

            var fileExtension = Path.GetExtension(fileName);
            if (!String.IsNullOrEmpty(fileExtension))
                fileExtension = fileExtension.ToLowerInvariant();
            var rand = new Random();
            var file = _filesService.InsertFile(fileBinary, fileExtension, DateTime.Now.ToString("yyyyMMddHHmmss") + rand.Next(10), titleAttribute: fileName);
            //when returning JSON the mime-type must be set to text/plain
            //otherwise some browsers will pop-up a "Save As" dialog.
            return Json(new
            {
                success = true,
                fileId = file.Id,
                fileUrl = _filesService.GetFileUrl(file)
            }, MimeTypes.TextPlain);
        }
    }
}